<template>
	<loading v-if="isLoading" style="height: 70vh;"></loading>
	<view class="tn-flex tn-flex-column" v-else>
		<tn-sticky class="tn-white_bg">
			<view class="tn-p-sm tn-pb-xs">
				<tn-search-box v-model="query.keyword" @search="getGoodList" @clear="getGoodList"
					search-button-bg-color="#F8F7F8" placeholder="请输入商品名称" search-button-text-color="#AAAAAA" />
			</view>
			<view class="tn-flex gap-2 tn-p-sm">
				<tn-input right-icon="right" v-model="sourceLabel" type="select" placeholder="筛选商品分类"
					@click="openSourcePicker=true" style="width: 250rpx;" />
				<view class="tn-flex gap-2">
					<tn-checkbox v-model="query.is_warning" :active-value="1" :inactive-value="0">警戒商品</tn-checkbox>
					<tn-button width="120" @click="getGoodList">查询</tn-button>
					<tn-button width="120" type="info" @click="reset">重置</tn-button>
				</view>
			</view>
			<view @click="showPopup=true"
				class="tn-flex items-center justify-between tn-p tn-pt-sm tn-white_bg border_bottom">
				<view class="tn-flex items-center">
					<tn-icon name="add-square" />
					<text class="tn-ml-xs">新增商品</text>
				</view>
				<tn-icon class="tn-text-right" type="info" name="right" />
			</view>
		</tn-sticky>
		<view class="empty" v-if="goodList.length==0">
			<image
				src="https://sgymv1.oss-cn-beijing.aliyuncs.com/sgym/avatar/admin/2025/02/a0c4966b-11af-4c87-93aa-359f9c03d89f83ee61eba8e363790692eb5fd8a98de7.png"
				mode="widthFix"></image>
			<text>这里空空荡荡，啥也没有留下</text>
		</view>
		<view v-else>
			<view class="tn-p tn-pb-sm border_bottom" v-for="item in goodList" :key="item.id"
				@click="editGoodInfo(item)">
				<view class="tn-flex items-center justify-between">
					<view class="tn-flex items-center">
						<tn-avatar shape="square"
							:url="item.goods_thumb?item.goods_thumb:'https://sgymv1.oss-cn-beijing.aliyuncs.com/sgym/avatar/admin/2024/11/9ccf98d5-b98d-4371-aeda-4cc50314d4e7453ab7651200438c6997a0665aec4063.png'"
							size="xl" />
						<view class="tn-ml-sm tn-flex tn-flex-column tn-text-xs tn-flex-1">
							<text class="tn-mr-xs tn-text-ellipsis-1">商品名称：{{item.goods_title}}</text>
							<text style="margin-top:1px" class="tn-text-ellipsis-1">商品单价：{{item.goods_price}} 元</text>
							<text style="margin-top:1px" class="tn-text-ellipsis-1">商品销量：{{item.sell_num}}
								{{item.unit}}</text>
							<text style="margin-top:1px" class="tn-text-ellipsis-1">
								在售库存：{{item.stock}} /
								<text style="color: #01BEFF;">实际库存：{{item.actual_stock}}</text>
							</text>
						</view>
					</view>
					<tn-icon class="tn-text-right" type="info" name="right" />
				</view>
				<view class="tn-flex justify-between items-end tn-mt-xs">
					<text style="color: #AAAAAA;font-size: 13px;">{{item.cate_name}}</text>
					<view class="tn-flex items-end">
						<text v-if="item.buy_max" style="color: #AAAAAA;font-size: 13px;margin-right: 20rpx;">限购
							{{item.buy_max}} 件</text>
						<tn-switch @change="changeActiveSwitch($event,'status',item)" v-model="item.status" size="sm"
							shape="square" :active-value="1" :inactive-value="0" active-text="上架"
							active-color="tn-green" inactive-text="下架" />
					</view>
				</view>
			</view>
			<view class="tn-pt-sm tn-pb-sm tn-flex-center">
				<uni-pagination :total="total" :current="query.page" :pageSize="query.limit" @change="changePage" />
			</view>
		</view>
	</view>
	<tn-popup v-model="showPopup" open-direction="bottom" @close="closePopup" close-btn>
		<view class="tn-pt">
			<view class="tn-pl-lg tn-pr-lg">
				<view class="popup_title">
					{{goodInfo.id?'编辑':'新增'}}商品
				</view>
			</view>
			<tn-subsection v-model="subsectionValue" size="lg" radius="0" mode="button" @change="changeSubsection"
				v-if="goodInfo.id" class="tn-mb">
				<tn-subsection-item title="商品详情" />
				<tn-subsection-item title="库存调整" />
				<tn-subsection-item title="调整记录" />
			</tn-subsection>
			<scroll-view scroll-y="true" style="max-height:70vh;min-height:70vh;">
				<template v-if="subsectionValue==0">
					<view class="tn-p-lg tn-pt-0">
						<tn-form :model="goodInfo" ref="formRef" :rules="formRules" label-position="top">
							<tn-form-item label="商品分类" prop="addSourceLabel">
								<tn-input right-icon="right" v-model="goodInfo.addSourceLabel" type="select"
									placeholder="筛选商品分类" @click="openAddSourcePicker=true" />
							</tn-form-item>
							<tn-form-item label="商品名称" prop="goods_title">
								<tn-input v-model="goodInfo.goods_title" placeholder="请输入商品名称" />
							</tn-form-item>
							<tn-form-item label="商品售价" prop="goods_price">
								<tn-input type="digit" v-model="goodInfo.goods_price" placeholder="请输入商品售价" clearable />
							</tn-form-item>
							<tn-form-item label="商品原价" prop="delete_price">
								<tn-input type="digit" v-model="goodInfo.delete_price" placeholder="请输入商品原价"
									clearable />
							</tn-form-item>
							<tn-form-item label="商品成本价" prop="cost_price">
								<tn-input type="digit" v-model="goodInfo.cost_price" placeholder="请输入商品成本价" clearable />
							</tn-form-item>
							<tn-form-item label="计量单位" prop="unit">
								<tn-radio-group v-model="goodInfo.unit">
									<tn-radio label="斤" border>斤</tn-radio>
									<tn-radio label="份" border>份</tn-radio>
								</tn-radio-group>
							</tn-form-item>
							<tn-form-item label="商品库存" prop="stock">
								<tn-input type="number" v-model="goodInfo.stock" placeholder="请输入商品库存" clearable />
							</tn-form-item>
							<tn-form-item label="商品限购（默认0代表不限购）" prop="buy_max">
								<tn-input type="number" v-model="goodInfo.buy_max" placeholder="请输入商品限购数量" clearable />
							</tn-form-item>
							<tn-form-item label="商品封面图">
								<tn-image-upload v-model="goodInfo.goods_thumb" :custom-upload-callback="uploadHandle"
									:action="actionUrl" :show-error-tips="false" :limit="1" />
							</tn-form-item>
							<tn-form-item label="商品轮播图">
								<tn-image-upload v-model="goodInfo.goods_thumbs" :custom-upload-callback="uploadHandle"
									:action="actionUrl" :show-error-tips="false" />
							</tn-form-item>
							<view class="gap"></view>
							<tn-form-item label="商品规格">
								<tn-input type="textarea" v-model="goodInfo.goods_spec" placeholder="请输入商品规格"
									clearable />
							</tn-form-item>
							<tn-form-item label="商品编码/条码">
								<tn-input v-model="goodInfo.goods_code" placeholder="请输入商品编码/条码" clearable />
							</tn-form-item>
							<tn-form-item label="产地">
								<tn-input v-model="goodInfo.goods_origin" placeholder="请输入产地" clearable />
							</tn-form-item>
							<tn-form-item label="材质">
								<tn-input v-model="goodInfo.goods_material" placeholder="请输入材质" clearable />
							</tn-form-item>
							<tn-form-item label="保质期">
								<tn-input v-model="goodInfo.goods_day" placeholder="请输入保质期" clearable />
							</tn-form-item>
						</tn-form>
						<view class="tn-flex-center">
							<tn-button size="lg" width="80vw" height="80" font-size="26"
								@click="submitForReview">{{goodInfo.id?'编辑':'新增'}}商品</tn-button>
						</view>
					</view>
				</template>
				<template v-if="subsectionValue==1">
					<zb-table :show-header="true" :columns="column" :stripe="true" :data="userTableData"
						class="tn-mb"></zb-table>
					<view class="tn-p-lg tn-pt-0">
						<tn-form :model="stockChange" ref="stockFormRef" :rules="stockFormRules" label-position="top">
							<tn-form-item label="调整类型" prop="type">
								<tn-radio-group v-model="stockChange.type">
									<tn-radio :label="1" border>采购入库</tn-radio>
									<tn-radio :label="3" border>盘点调整</tn-radio>
									<tn-radio :label="4" border>退货其他</tn-radio>
								</tn-radio-group>
							</tn-form-item>
							<tn-form-item label="调整数量" prop="quantity">
								<tn-input type="number" v-model="stockChange.quantity" placeholder="请输入调整数量（大于0增加小于0减少）"
									clearable />
							</tn-form-item>
							<tn-form-item label="关联单号">
								<tn-input v-model="stockChange.order_no" placeholder="请输入关联订单号" clearable />
							</tn-form-item>
							<tn-form-item label="备注说明">
								<tn-input type="textarea" height="200" show-word-limit :maxlength="50"
									v-model="stockChange.remark" placeholder="请输入备注说明" clearable />
							</tn-form-item>
						</tn-form>
						<view class="tn-flex-center">
							<tn-button size="lg" width="80vw" height="80" font-size="26"
								@click="changeGoodsStock">确定</tn-button>
						</view>
					</view>
				</template>
				<template v-if="subsectionValue==2">
					<view class="tn-p tn-pt-0 tn-pb-0">
						<view class="tn-flex gap-2">
							<tn-input v-model="recordQuery.start" type="select" right-icon="right" placeholder="请选择开始日期"
								@click="openStartDateTimePicker=true" />
							<tn-input v-model="recordQuery.end" type="select" right-icon="right" placeholder="请选择结束日期"
								@click="openEndDateTimePicker=true" />
						</view>
						<view class="tn-flex justify-between items-center gap-2 tn-mt">
							<view class="">
								<tn-icon name="ticket" class="tn-mr-xs"></tn-icon>
								<text>共 {{recordListTotal}} 条记录</text>
							</view>
							<view class="tn-flex gap-2">
								<tn-button width="120" height="75" @click="getChangeStockLogs">查询</tn-button>
								<tn-button width="120" height="75" type="info" @click="resetStockLogs">重置</tn-button>
							</view>
						</view>
					</view>
					<view class="empty" v-if="recordList.length==0">
						<image
							src="https://sgymv1.oss-cn-beijing.aliyuncs.com/sgym/avatar/admin/2025/02/a0c4966b-11af-4c87-93aa-359f9c03d89f83ee61eba8e363790692eb5fd8a98de7.png"
							mode="widthFix"></image>
						<text>这里空空荡荡，啥也没有留下</text>
					</view>
					<view v-for="item in recordList" :key="item.id" class="tn-p border_bottom" v-else>
						<view class="tn-flex">
							<view class="tn-round tn-flex tn-flex-center tn-p-xs tn-type-primary_bg"
								style="width: 40rpx;height: 40rpx;">
								<tn-icon name="pushpin-fill" size="28" />
							</view>
							<view class="tn-flex tn-flex-column tn-ml-sm">
								<text class="tn-text-bold tn-text-lg">{{item.type_text}}</text>
								<text class="tn-gray-dark_text tn-text-sm tn-mt-xs">操作人员：{{item.admin_name}}</text>
								<view class="tn-flex items-center">
									<text class="tn-gray-dark_text tn-text-sm tn-mt-xs">
										调整数量：<text
											:style="{color:item.quantity>0?'#00D886':'#FF444F'}">{{item.quantity}}</text>
									</text>
									<text
										class="tn-gray-dark_text tn-text-sm tn-mt-xs">&nbsp;&nbsp;&nbsp;/&nbsp;&nbsp;&nbsp;剩余数量：{{item.stock_after}}</text>
								</view>
								<text class="tn-gray-dark_text tn-text-sm tn-mt-xs"
									v-if="item.remark">备注说明：{{item.remark}}</text>
								<text class="tn-gray-dark_text tn-text-sm tn-mt-xs">操作时间：{{item.add_time}}</text>
							</view>
						</view>
					</view>
					<view class="tn-pt-sm tn-pb-sm tn-flex-center">
						<uni-pagination :total="recordListTotal" :current="recordQuery.page"
							:pageSize="recordQuery.limit" @change="changeRecordPage" />
					</view>
				</template>
				<view style="height: 100rpx;"></view>
			</scroll-view>
		</view>
	</tn-popup>
	<tn-picker v-model="query.cate_id" v-model:open="openSourcePicker" :data="categoryList" @confirm="confirmPicker"
		label-key="cate_name" value-key="id" />
	<tn-picker v-model="goodInfo.cate_id" v-model:open="openAddSourcePicker" :data="categoryList"
		@confirm="confirmAddPicker" label-key="cate_name" value-key="id" />
	<tn-date-time-picker v-model="recordQuery.start" v-model:open="openStartDateTimePicker" format="YYYY-MM-DD"
		:init-current-date-time="false" />
	<tn-date-time-picker v-model="recordQuery.end" v-model:open="openEndDateTimePicker" format="YYYY-MM-DD"
		:init-current-date-time="false" />
	<tn-modal ref="modalRef" />
</template>

<script setup>
	import {
		getSpecialsGoodListApi,
		getSpecialsCategoryListApi,
		specialGoodsUpdateApi,
		specialsGoodAddOrEditApi,
		changeGoodsStockApi,
		getChangeStockLogsApi
	} from "@/request/worktop/system.js"
	import {
		ref,
		onMounted
	} from 'vue';
	import {
		base_url,
		domain_name,
		uploadHandle
	} from "@/request/index.js"

	onMounted(() => {
		getSpecialsCategoryList()
	})

	const actionUrl = base_url + '/index/upload'

	const formRef = ref()
	const stockFormRef = ref()
	const modalRef = ref()

	const showPopup = ref(false)
	const isLoading = ref(true)
	const goodInfo = ref({
		id: 0,
		cate_id: 0,
		cate_id2: 0,
		goods_title: '',
		goods_price: '',
		delete_price: '',
		cost_price: '',
		stock: '',
		unit: '斤',
		buy_max: 0,
		addSourceLabel: '',
		goods_thumb: [],
		goods_thumbs: [],
		goods_spec: "",
		goods_code: "",
		goods_origin: "",
		goods_material: "",
		goods_day: ""
	})
	const stockChange = ref({
		id: 0,
		type: 1,
		quantity: '',
		remark: '',
		order_no: ''
	})
	const query = ref({
		page: 1,
		limit: 20,
		keyword: '',
		cate_id: 0,
		cate_id2: 0,
		is_warning: 0,
	})
	const total = ref(0)
	const categoryList = ref([])
	const goodList = ref([])
	const openSourcePicker = ref(false)
	const openAddSourcePicker = ref(false)
	const sourceLabel = ref('')

	const subsectionValue = ref(0)

	const logsLoading = ref(true)
	const column = ref([{
			name: 'goods_stock1',
			label: '采购入库',
			align: 'center'
		},
		{
			name: 'goods_stock2',
			label: '销售出库',
			align: 'center'
		},
		{
			name: 'goods_stock3',
			label: '盘点调整',
			align: 'center'
		},
		{
			name: 'goods_stock4',
			label: '退货其他',
			align: 'center'
		},
	])
	const userTableData = ref([])

	const recordQuery = ref({
		page: 1,
		limit: 10,
		goods_id: 0,
		start: '',
		end: ''
	})
	const recordList = ref([])
	const recordListTotal = ref(0)
	const openStartDateTimePicker = ref(false)
	const openEndDateTimePicker = ref(false)

	// 获取商品列表
	const getGoodList = () => {
		getSpecialsGoodListApi(query.value).then(res => {
			total.value = res.other.total
			goodList.value = res.data
		}).catch(err => {
			uni.showToast({
				title: err.message,
				icon: 'none'
			})
		}).finally(() => {
			setTimeout(() => {
				isLoading.value = false
			}, 500)
		})
	}
	// 获取商品分类列表
	const getSpecialsCategoryList = () => {
		getSpecialsCategoryListApi(query.value).then(res => {
			total.value = res.other.total
			categoryList.value = res.data
			getGoodList()
		}).catch(err => {
			uni.showToast({
				title: err.message,
				icon: 'none'
			})
		}).finally(() => {
			setTimeout(() => {
				isLoading.value = false
			}, 500)
		})
	}
	// 规则
	const formRules = {
		addSourceLabel: [{
			required: true,
			message: '请输入分类名称',
			trigger: ['change', 'blur']
		}],
		goods_title: [{
			required: true,
			message: '请输入商品名称',
			trigger: ['change', 'blur']
		}],
		goods_price: [{
			required: true,
			message: '请输入商品售价',
			trigger: ['change', 'blur']
		}, {
			pattern: /^(0\.0[1-9]|0\.[1-9]\d?|[1-9]\d{0,3}(\.\d{1,2})?)$/,
			message: '价格需在0.01-9999之间，最多两位小数',
			trigger: ['change', 'blur']
		}],
		delete_price: [{
			required: true,
			message: '请输入商品原价',
			trigger: ['change', 'blur']
		}, {
			pattern: /^(0\.0[1-9]|0\.[1-9]\d?|[1-9]\d{0,3}(\.\d{1,2})?)$/,
			message: '价格需在0.01-9999之间，最多两位小数',
			trigger: ['change', 'blur']
		}],
		cost_price: [{
			required: true,
			message: '请输入商品成本价',
			trigger: ['change', 'blur']
		}, {
			pattern: /^(0\.0[1-9]|0\.[1-9]\d?|[1-9]\d{0,3}(\.\d{1,2})?)$/,
			message: '价格需在0.01-9999之间，最多两位小数',
			trigger: ['change', 'blur']
		}],
		buy_max: [{
			required: true,
			message: '请输入限购数量（0不限购）',
			trigger: ['change', 'blur']
		}, {
			pattern: /^\d{1,4}$/,
			message: '请输入0-9999之间的数字',
			trigger: ['change', 'blur'],
		}],
		stock: [{
			required: true,
			message: '请输入商品库存',
			trigger: ['change', 'blur']
		}, {
			pattern: /^\d{1,4}$/,
			message: '请输入0-9999之间的数字',
			trigger: ['change', 'blur'],
		}],
		unit: [{
			required: true,
			message: '请输入商品计量单位',
			trigger: ['change', 'blur']
		}],
	}
	// 调整库存规则
	const stockFormRules = {
		quantity: [{
			required: true,
			message: '请输入调整数量（大于0增加小于0减少）',
			trigger: ['change', 'blur']
		}],
	}
	// 新增/编辑商品
	const submitForReview = () => {
		formRef.value?.validate((valid) => {
			if (valid) {
				let obj = JSON.parse(JSON.stringify(goodInfo.value))
				obj.goods_thumb = obj.goods_thumb.join().replace(new RegExp(domain_name, 'g'), '')
				obj.goods_thumbs = obj.goods_thumbs.map(url => url.replace(new RegExp(domain_name, 'g'), ''))
				specialsGoodAddOrEditApi(obj).then(res => {
					if (res.code == 0) {
						uni.showToast({
							title: res.message,
							mask: true,
							success() {
								setTimeout(() => {
									showPopup.value = false
									getGoodList()
								}, 800)
							}
						})
					}
				}).catch(err => {
					uni.showToast({
						title: err.message,
						icon: "none"
					})
				})
			} else {
				uni.showToast({
					title: '请检查必填项',
					icon: 'error',
				})
			}
		})
	}
	// 切换开关
	const changeActiveSwitch = (value, type, item) => {
		let obj = {
			id: item.id,
			field: type,
			value: value
		}
		specialGoodsUpdateApi(obj).then(res => {
			if (res.code == 0) {
				uni.showToast({
					title: res.message,
				})
			}
		}).catch(() => {
			uni.showToast({
				title: err.message,
				icon: 'none',
				success() {
					setTimeout(() => {
						getGoodList()
					}, 800)
				}
			})
		})
	}
	// 确定选择来源
	const confirmPicker = (_, item) => {
		sourceLabel.value = item.cate_name
	}
	// 新增商品确定选择来源
	const confirmAddPicker = (_, item) => {
		goodInfo.value.addSourceLabel = item.cate_name
	}
	// 重置按钮
	const reset = () => {
		sourceLabel.value = ''
		query.value.keyword = ''
		query.value.cate_id = 0
		query.value.cate_id2 = 0
		query.value.is_warning = 0
		getGoodList()
	}
	// 重置调整库存记录按钮
	const resetStockLogs = () => {
		recordQuery.value.start = ''
		recordQuery.value.end = ''
		getChangeStockLogs()
	}
	// 更新页码
	const changePage = (e) => {
		query.value.page = e.current
		getGoodList()
	}
	// 更新库存页码
	const changeRecordPage = (e) => {
		recordQuery.value.page = e.current
		getChangeStockLogs()
	}
	// 弹出层关闭
	const closePopup = () => {
		goodInfo.value = {
			id: 0,
			cate_id: 0,
			cate_id2: 0,
			goods_title: '',
			goods_price: '',
			delete_price: '',
			cost_price: '',
			stock: '',
			unit: '斤',
			buy_max: 0,
			addSourceLabel: '',
			goods_thumb: [],
			goods_thumbs: [],
			goods_spec: "",
			goods_code: "",
			goods_origin: "",
			goods_material: "",
			goods_day: ""
		}
		subsectionValue.value = 0
		stockChange.value = {
			id: 0,
			type: 1,
			quantity: '',
			remark: '',
			order_no: ''
		}
		recordList.value = []
		formRef.value?.resetFields()
		stockFormRef.value?.resetFields()
	}
	// 编辑商品
	const editGoodInfo = (item) => {
		const obj = JSON.parse(JSON.stringify(item))
		obj.addSourceLabel = categoryList.value.find(i => i.id == obj.cate_id).cate_name
		obj.goods_thumb = obj.goods_thumb.split()
		goodInfo.value = obj
		stockChange.value.id = obj.id
		recordQuery.value.goods_id = obj.id
		showPopup.value = true
	}
	// 调整库存
	const changeGoodsStock = () => {
		changeGoodsStockApi(stockChange.value).then(res => {
			if (res.code == 0) {
				uni.showToast({
					title: res.message,
					success() {
						setTimeout(() => {
							showPopup.value = false
							getGoodList()
						}, 800)
					}
				})
			}
		}).catch(err => {
			uni.showToast({
				title: err.message,
				icon: "none"
			})
		})
	}
	// 获取库存调整记录
	const getChangeStockLogs = () => {
		getChangeStockLogsApi(recordQuery.value).then(res => {
			if (res.code == 0) {
				recordList.value = res.data
				recordListTotal.value = res.other.total
			}
		}).catch(err => {
			uni.showToast({
				title: err.message,
				icon: "none"
			})
		})
	}
	// 切换标题
	const changeSubsection = (index) => {
		if (index == 1) {
			userTableData.value = [{
				goods_stock1: goodInfo.value.goods_stock1,
				goods_stock2: goodInfo.value.goods_stock2,
				goods_stock3: goodInfo.value.goods_stock3,
				goods_stock4: goodInfo.value.goods_stock4
			}]
		} else if (index == 2) {
			getChangeStockLogs()
		}
	}
</script>

<style scoped lang="scss">
</style>